﻿using AutoMapper;
using Domain.Models;
using Extensions.Attributes;
using IRepository;
using IServices;
using Services.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using ViewModel.Auth;

namespace Services
{
    public class AccountService : BaseService<Domain.Models.Account>, IAccountService
    {
        protected readonly IAccountRepository accountRepository;

        public AccountService(IAccountRepository accountRepository, IMapper mapper) : base(mapper)
        {
            this.accountRepository = accountRepository;
            base.baseRepository = accountRepository;
        }



        public bool Login(string username, string password)
        {
            var queryUser = this.accountRepository.Query(x => x.UserName == username).FirstOrDefault();
            if (queryUser == null)
            {
                return false;
            }
            var entryPassword = BitConverter.ToString(
                new MD5CryptoServiceProvider()
                .ComputeHash(Encoding.UTF8.GetBytes(password))).Replace("-", "");
            if (!string.Equals(entryPassword, queryUser.Password))
            {
                return false;
            }
            return true;
        }
        public bool Login(AuthModel authModel)
        {
            return this.Login(authModel.UserName, authModel.Password);
        }

        [Caching]
        public IEnumerable<ViewModel.AccountModel.Account> GetAccounts()
        {
            return this.mapper.Map<IEnumerable<Account>, IEnumerable<ViewModel.AccountModel.Account>>(this.accountRepository.Query());
        }

    }
}
